<template>
    <!-- 搜索  添加 -->
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
        <el-form-item label="用户名">
            <el-input v-model="queryInfo.userUserName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="用户昵称">
            <el-input v-model="queryInfo.userNickName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="手机号">
            <el-input v-model="queryInfo.userPhone" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getUserList">搜索</el-button>
            <el-button @click="toAdd" type="primary" icon="Plus" plain>新增</el-button>
        </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100% ;text-align: center;">
        <el-table-column prop="userId" label="编号" width="80" />
        <el-table-column prop="userUserName" label="用户账户" />
        <el-table-column prop="userNickName" label="用户昵称" />
        <el-table-column prop="userName" label="用户名称" />
        <el-table-column prop="userEmail" label="邮箱" />
        <el-table-column prop="userPhone" label="手机号" />
        <el-table-column prop="userAddress" label="地址" />
        <el-table-column prop="userPoint" label="积分" />
        <<el-table-column label="操作" width="200px ">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.row)">
                    修改
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row.userId)">
                    删除
                </el-button>
            </template>
            </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
        v-model:current-page="queryInfo.pageNum"
        v-model:page-size="queryInfo.pageSize"
        :page-sizes="[1, 5, 10, 20]"
        :size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

<!-- 添加修改 对话框 -->
    <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle"  width="500" @close="close">
        <el-form :model="user" :rules="rules" status-icon ref="ruleFormRef" >
            <el-form-item label="用户名称" prop="userName" :label-width="formLabelWidth">
                <el-input v-model="user.userName" autocomplete="off" />
            </el-form-item>
            <el-form-item v-if="power" label="用户账号" prop="userUserName" :label-width="formLabelWidth" >
                <el-input v-model="user.userUserName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户密码" prop="userPassword" :label-width="formLabelWidth">
                <el-input v-model="user.userPassword" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户昵称" prop="userNickName" :label-width="formLabelWidth">
                <el-input v-model="user.userNickName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" prop="userPhone" :label-width="formLabelWidth">
                <el-input v-model="user.userPhone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="userEmail" :label-width="formLabelWidth">
                <el-input v-model="user.userEmail" autocomplete="off" />
            </el-form-item>
            <el-form-item label="地址" prop="userAddress" :label-width="formLabelWidth">
                <el-input v-model="user.userAddress" autocomplete="off" />
            </el-form-item>
        </el-form>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="saveOrUpdate">
                确定
                </el-button>
            </div>
            </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted,reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
const ruleFormRef = ref(null);
const queryInfo = ref({
    pageNum: 1,
    pageSize: 5,
    userUserName: '',
    userNickName: '',
    userPhone: ''
})
const user = ref({     
    userName:'',
    userPassword:'',
    userUserName: '',
    userNickName: '',
    userPhone: '',
    userEmail: '', 
    userAddress: '',
    userPoint: '0'
})
const tableData = ref([])
const total = ref()
const saveOrUpdateVisible= ref(false)
const saveOrUpdateTitle = ref('')
// 修改权限 账号不能改
const power =ref(false)
const formLabelWidth = '80px'

// 表单验证规则
const rules = reactive({
  // 用户名验证
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  // 用户账号验证
  userUserName: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 3, max: 20, message: '用户账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  // 用户密码验证
  userPassword: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为 6 个字符', trigger: 'blur' }
  ],
  // 用户昵称验证
  userNickName: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '用户昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  // 手机号验证
  userPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  // 邮箱验证
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  // 地址验证
  userAddress: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, message: '地址长度至少为 5 个字符', trigger: 'blur' }
  ]
});
// 确定
const saveOrUpdate = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (saveOrUpdateTitle.value === '添加用户表') {
        axios.post('/user/add', user.value)
          .then(resp => {
            let result = resp.data;
            if (result.code === 1) {
              getUserList();
              ElMessage.success('添加用户成功');
            } else {
              ElMessage.warning('添加用户失败');
            }
          });
      } else {
        axios.put('/user/edit', user.value)
          .then(resp => {
            let result = resp.data;
            if (result.code === 1) {
              getUserList();
              ElMessage.success('修改用户成功');
            } else {
              ElMessage.warning('修改用户失败');
            }
          });
      }
      close();
    } else {
      ElMessage.warning('表单验证失败，请检查输入');
    }
  });
};
// 取消
const close=()=>{
    saveOrUpdateVisible.value = false;
    user.value = {
        userName:'',
        userPassword:'',
        userUserName: '',
        userNickName: '',
        userPhone: '',
        userEmail: '',
        userAddress: '',
        userPoint: '0'
    }
    ruleFormRef.value.clearValidate()
}
// 添加
const toAdd=()=>{
    saveOrUpdateTitle.value = '添加用户表'
    saveOrUpdateVisible.value = true
    power.value = true
    console.log(saveOrUpdateVisible.value)
}
// 修改
const handleEdit = (row) => {
    saveOrUpdateTitle.value = '修改用户表'
    saveOrUpdateVisible.value = true
    power.value = false
    user.value = row
}
// 分页
// 当用户改变每页显示的条目数时触发
const handleSizeChange = (pageSize) => {
  queryInfo.value.pageSize = pageSize;
  getUserList();
}
// 当用户改变当前页码时触发
const handleCurrentChange = (pageNum) => {
  queryInfo.value.pageNum = pageNum;
  getUserList();
}
// 定义一个页面加载函数
onMounted(() => {
    getUserList();
})
const getUserList = () => {
    axios.get('/user/findByPage', { params: queryInfo.value })
        .then(resp => {
            let result = resp.data;
            total.value = result.data.total;
            if (result.code == 1) {
                tableData.value = result.data.list
            } else {
                console.log('获取用户列表失败')
            }
        })
}
// 删除用户
const handleDelete = (userId) => {
    ElMessageBox.confirm(
        '真的要删除吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
        .then(() => {
            axios.delete('/user/remove', {
                params: { userId: userId }
            })
                .then(resp => {
                    let result = resp.data;
                    if (result.code == 1) {
                        getUserList();
                        ElMessage({
                            message: '删除成功！',
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: '删除失败！',
                        })
                    }
                })
        })

}
</script>

<style setup>
.el-table .cell{text-align: center;}
.el-table-column{text-align: center;}
</style>